from langchain.output_parsers import OutputFixingParser
from langchain_core.output_parsers import PydanticOutputParser
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field
from typing import List
from  langchain_core.prompts import PromptTemplate

# 定义模型
model = ChatOpenAI(
    model_name = "qwen-plus",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
    api_key="sk-005c3c25f6d042848b29d75f2f020f08",
    temperature=0.7
)

class Actor(BaseModel):
    name: str = Field(description="演员姓名")
    film_names: List[str] = Field(description="参演电影列表")

parser = PydanticOutputParser(pydantic_object=Actor)


#定义PromptTemplate
prompt = PromptTemplate(
    template="{format_instructions} \n {query}",
    input_variables=["query"],
    partial_variables={"format_instructions": parser.get_format_instructions()},
)

#包装原是解析器
fixing_parser = OutputFixingParser.from_llm(parser=parser, llm=model,max_retries=5)
chain = prompt | model | fixing_parser
response = chain.invoke({"query":"说出成龙演过的5部动作电影?"})
print(response)
print(type(response))
print(response.json())
